import {getMDAppVersion} from "@/utils";
import {io} from "socket.io-client";
import {v4 as uuidv4} from "uuid";


// 秤状态
const scalesStateMap = {
  search: 'search',
  connected: 'connected',
  discontented: 'discontented',
  error: 'error',
  transform: 'transform',
}

export default {
  name: 'hardware',
  data(){
    return {
      appVersion: getMDAppVersion(), // 软件的版本号
      appLink: false, // 是否启动了软件
      // 校验app相关信息
      appCheckStatus: {
        appStart: false, // 是否启动了APP （包含连接）
        printersState: false, // 是否正常获取系统的打印机（只判断获取，不判断系统有多少个打印机）
        scalesState: '', // 电子秤状态
        appVersion: null, // 用于判断版本是否相同
      },
      socket: null, // socket 对象
      scaleDeviceInfo: null,
      printers: [], // 所有的打印机
      currentPrinter: null, // 默认的打印机
      printerInterval: null, // 定时器
      scannerTest: '', // 扫描枪和自定义输入扫码内容
      currentPrinterStatus: 0, // 当前打印状态 -1打印异常 0待打印 1请求PDF接口 2正在打印 3打印完成
      scalesWeight: 0, // 电子秤的重量
    }
  },
  created() {
    this.linkApp()
  },
  methods: {
    linkApp(){
      new Promise((resolve, reject) => {
        this.socket = io('ws://127.0.0.1:18232');
        this.socket.on('connect', () => {
          this.appCheckStatus.appStart = true
          // 初始化数据
          this.serverDataInit()
        });
        this.socket.on('connect_error', (error) => {
          console.log('connect_error')
          // this.addMessage(false, "服务器连接错误");
        });
        this.socket.on('error', (error) => {
          console.error("An error occurred:", error);
        });
        this.socket.on('disconnect', (reason) => {
          // this.addMessage(false, "服务器断开链接");
          // console.log('disconnect')
          this.resetDataInit()
        });

        // 接收 'message' 事件
        this.socket.on('message', (message) => {
          if (!message || !message.type || !message.data) {
            console.error("接收信息错误", message);
            return;
          }
          const uuid = message.uuid
          const data = message.data;

          switch (message.type) {
            // 打印机配置
            case 'printerConfigs':
              if (data.error === 0) {
                this.printers = data.printerList;
                // this.addMessage(true, '获取系统打印机成功');
                if (this.printers && !this.currentPrinter) {
                  this.printers.some(printer => {
                    if (printer.isDefault) {
                      // this.addMessage(true, '选择默认打印机');
                      this.currentPrinter = printer;
                      return true;
                    }
                  });
                }
                this.appCheckStatus.printersState = true;
              } else {
                // console.log('获取系统打印机失败' + data.message);
                // this.addMessage(false, '获取系统打印机失败' + data.message);
                this.appCheckStatus.printersState = false;
                this.currentPrinter = null
              }
              break;

            // 打印结果
            case 'printResult':
              if (data.error === 0) {
                this.currentPrinterStatus = 3
                this.printSuccess();
                if(this.printerPDFType === 2){
                  this.printerTestLoading = false
                }
              } else {
                this.printError();
                this.currentPrinterStatus = -1
              }
              break;
            // 电子秤状态
            case 'state':
              if (data.error === 0) {
                // console.log('scales state', data.info.state);
                this.scaleDeviceInfo = data.info;
                this.appCheckStatus.scalesState = data.info.state;
              } else {
                // console.log('电子秤状态异常', data.message);
                this.scalesWeight = 0;
                this.appCheckStatus.scalesState = scalesStateMap.error;
              }
              break;

            // 电子秤读数
            case 'weight':
              this.scalesWeight = this.formatWeight(data.text);
              break;

            // 客户端状态
            case 'clientState':
              this.clientConnected = !!(data && data.connected);
              break;

            // 版本
            case 'version':
              this.appCheckStatus.appVersion = data.version
              break;

            // 其他异常状态
            case 'paramsError':
              console.error('paramsError', data.message, message.uuid)
              break;
            case 'systemError':
              console.error('systemError', data.message, message.uuid)
              break;

            default:
              console.error("接收信息异常", message);
              break;
          }


        });
      })
    },
    // 发送信息
    sendSocket(type, data = null, uuid = null) {
      if (this.socket && this.socket.connected) {
        if (uuid === null) {
          uuid = uuidv4();
        }

        // console.log("发送： " + type + uuid);
        const message = {
          type,
          uuid,
          data,
          timestamp: (new Date()).getTime(),
        };
        this.socket.emit('message', message);
      }
    },
    // 服务数据初始化
    serverDataInit() {
      // 打印机每30s 获取一次打印机配置
      this.sendSocket('getVersion');
      this.sendSocket('getPrinterConfigs');
      this.printerInterval = setInterval(() => {
        this.sendSocket('getPrinterConfigs');
      }, 30000);

      // 开始获取一次秤的状态
      this.sendSocket('getState');
    },
    resetDataInit(){
      if(this.printerInterval){
        clearInterval(this.printerInterval)
      }
      this.appCheckStatus.appStart = false;
      this.appCheckStatus.printersState = false;
      this.appCheckStatus.scalesState = '';
      this.appCheckStatus.appVersion = null;
      this.appStartDialog = true
    },
    // 将电子秤读取的字符 转成对应的数字
    formatWeight(text){
      const unit = text.slice(-2);
      let weight = 0;
      if(unit === 'kg'){
        weight = Number(text.slice(0,-2)) * 1000
      }else if(unit === 'lb'){
        weight = Number(text.slice(0,-2)) * 453.59237
      }else{
        weight = Number(text.slice(0,-1))
      }
      return Math.ceil(weight)
    },
    printSuccess(){

    },
    printError(){

    },
  },
  destroyed() {
    if (this.socket && this.socket.connected) {
      this.socket.close();
    }
    if(this.printerInterval){
      clearInterval(this.printerInterval)
    }
  },
}
